/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.SystemProperty;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class SystemPropertiesBean implements SystemPropertiesLocal {

    @PersistenceContext
    private EntityManager em;

    public List<SystemProperty> findAllSystemProperties(KeyLocal key) {
        key.validateKey();
        return em.createNamedQuery("findAllSystemProperties").getResultList();
    }

    /**
     * Sets up the table of system property types. Value objects with valid IDs
     * will be edited. Those without valid IDs are new and will be created.
     * Existing types that are not in the collection will be deleted.
     *
     * @param key User's security key
     * @param systemProperties Collection of system property value objects
     **/
    public void setSystemProperties(KeyLocal key, Collection<SystemProperty> systemProperties) {
        key.validateKey();
        Collection<SystemProperty> existingProperties = em.createNamedQuery("findAllSystemProperties").getResultList();
        for (SystemProperty systemProperty: systemProperties) {
            // update existing ones
            if (systemProperty.getId() != null) {
                SystemProperty currentProperty = em.find(SystemProperty.class, systemProperty.getId());
                if (currentProperty.isEditable())
                    em.merge(systemProperty);
                existingProperties.remove(currentProperty);
            }
            // create new ones
            else {
                em.persist(systemProperty);
            }
        }
        // delete remaining ones
        for (SystemProperty systemProperty: existingProperties) {
            em.remove(systemProperty);
        }
    }


    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method" or "Web Service > Add Operation")
 
}
